# coding=utf-8
# 代码文件：chapter2/ch2.3.py
import os
import urllib.request

# 请求数据的URL网址
url = 'http://quotes.money.163.com/service/chddata.html?code={0}&start={1}&end={2}&fields={3}'

# 设置请求数据的字段
fields = 'TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP'
# 传递参数获得最终URL网址
strURL = url.format('0600519', '20010827', '20210323', fields)
print("请求的URL：", strURL)

req = urllib.request.Request(strURL)

with urllib.request.urlopen(req) as response:
    dataStr = response.read().decode(encoding='gbk', errors='ignore')
    print(dataStr)

    # 如果data文件夹不存在，则创建
    if not os.path.exists('data'):
        os.mkdir('data')
    fileName = '贵州茅台股票历史交易数据.csv'
    filePath = 'data/' + fileName

    with open(filePath, 'w+') as f:
        f.write(dataStr)
    print('下载文件成功')